from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from user.models import User, UserInfo
from django.contrib.auth import logout, login
from user.forms import UserInfoForm


@csrf_exempt
def to_login(request):
    if request.method == "POST":
        post = request.POST
        user = User.objects.filter(phone=post.get('phone'), password=post.get('password'))
        if user:
            login(request, user[0])
            return redirect('/user/home')
        else:
            message = '账号或密码不正确，请检查！'
            return render(request, 'user/login.html', locals())
    else:
        return render(request, 'user/login.html')


@csrf_exempt
def register(request):
    if request.method == "POST":
        post = request.POST
        if post.get('password') != post.get('password1'):
            message = '两次密码输入不一致！'
            return render(request, 'user/register.html', locals())
        elif User.objects.filter(phone=post.get('phone')):
            message = '手机号已经被注册！'
            return render(request, 'user/register.html', locals())
        else:
            user = User.objects.create(phone=post.get('phone'),
                                       password=post.get('password'),
                                       username=post.get('phone'))
            user_info = UserInfo.objects.create(user=user)
            login(request, user)
            return redirect('user/base')
    else:
        return render(request, 'user/register.html')

def out(request):
    logout(request)
    return redirect('/bbs')

def home(request):
    return render(request, 'user/home.html')

def base(request):
    title = '个人设置-社区-量子企业数据智能分析系统-专注企业加速'
    user_info = UserInfo.objects.filter(user_id=request.user.id)[0]
    form = UserInfoForm(instance= user_info)
    if request.method == "POST":
        return render(request, 'user/base.html')
    else:
        return render(request, 'user/base.html', locals())